package com.gonsin.easycount.config;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * Redis使用FastJson序列化
 */
public class JsonSerializer<T>  {

    public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    private Type clazz;

    public JsonSerializer(Type clazz) {
        super();
        this.clazz = clazz;
    }

    public String serialize(T t)  {
        if (t == null) {
            return "";
        }
//        return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName);
        return new Gson().toJson(t);
    }

    public T deserialize(String str) {
//        if (bytes == null || bytes.length <= 0) {
//            return null;
//        }
//        String str = new String(bytes, DEFAULT_CHARSET);
        if(str == null || "".equals(str)){
            return null;
        }


        return new Gson().fromJson(str, clazz);

//        return JSON.parseObject(str, clazz, JSONReader.Feature.SupportAutoType);
    }
}
